package com.cloudinnov.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.cloudinnov.model.AreaObject;

/**
 * @author chenning
 * @date 2016年8月5日下午3:25:09
 * @email 
 * @remark 获取区域的工具类（可能是）
 * @version 
 */
public class AreasUtil {
	// 获取一级节点
	public Map<String, Object> returnAreaData(List<AreaObject> list,
			int parentId) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> returnList = new HashMap<String, Object>();
		for (Iterator<AreaObject> iterator = list.iterator(); iterator
				.hasNext();) {
			AreaObject t = (AreaObject) iterator.next();
			if (t.getParentId().equals(parentId)) {
				// 获取二级节点
				returnList = secondPoint(list, t);
				returnMap.put(t.getName(), returnList);
			}
		}
		return returnMap;
	}

	// 获取二级节点方法
	public Map<String, Object> secondPoint(List<AreaObject> list, AreaObject ao) {
		// 获取子节点
		List<AreaObject> childrenList = getChildrenList(list, ao);
		List<Object> seList = new ArrayList<Object>();
		Map<String, Object> temporaryMap = new HashMap<String, Object>();
		// 遍历子节点
		if (childrenList.size() > 0) {
			for (AreaObject tChild : childrenList) {
				if (hasChild(list, tChild)) {
					// 获取三级节点
					seList = thirdPoint(list, tChild);
				}
				temporaryMap.put(tChild.getName(), seList);
				seList = new ArrayList<Object>();
			}
		}

		return temporaryMap;
	}

	// 获取三级节点
	public List<Object> thirdPoint(List<AreaObject> list, AreaObject ao) {
		List<Object> returnList = new ArrayList<Object>();
		Iterator<AreaObject> it = list.iterator();
		while (it.hasNext()) {
			AreaObject n = (AreaObject) it.next();
			if (n.getParentId().equals(ao.getId())) {
				returnList.add(n.getName());
			}
		}
		return returnList;
	}

	public List<AreaObject> getChildrenList(List<AreaObject> list, AreaObject ao) {
		List<AreaObject> tlist = new ArrayList<AreaObject>();
		Iterator<AreaObject> it = list.iterator();
		while (it.hasNext()) {
			AreaObject n = (AreaObject) it.next();
			if (n.getParentId().equals(ao.getId())) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	public boolean hasChild(List<AreaObject> list, AreaObject ao) {
		List<AreaObject> tlist = getChildrenList(list, ao);
		return tlist.size() > 0 ? true : false;
	}
}
